﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace ChatForum.Client
{
    internal class PageHelper
    {
        internal static Control FindControlRecursive(Control container, string name)
        {
            if (container.ID == name)
                return container;

            foreach (Control ctrl in container.Controls)
            {
                Control foundCtrl = FindControlRecursive(ctrl, name);
                if (foundCtrl != null)
                    return foundCtrl;
            }
            return null;
        }
        internal static void HideControl(Control container, string controlId)
        {
            HtmlGenericControl control = (HtmlGenericControl)FindControlRecursive(container, controlId);
            if (control != null)
                control.Style.Add("display", "none");
		}
		internal static T CastToObject<T>(GridViewRow row, string sessionVariable)
		{
			int ri = row.RowIndex;
			int di = row.DataItemIndex;
			List<T> objList = (List<T>)HttpContext.Current.Session[sessionVariable];
			return objList[ri];
		}
		internal static List<T> GetSelectedObjectFromGrid<T>(Control container, string gridId, string sessionVariable, string selectorControlId)
		{
			GridView grid = (GridView)FindControlRecursive(container, gridId);
			List<T> objList = new List<T>();
			foreach (GridViewRow row in grid.Rows)
			{
				CheckBox selector = (CheckBox)row.FindControl(selectorControlId);
				if (selector != null && selector.Checked)
				{
					objList.Add(CastToObject<T>(row, sessionVariable));
				}
			}
			return objList;
		}
    }
}